<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-03-05
 * @Time: 16:52
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： AskLiked.php
 */
namespace app\api\model\ask;

use think\Db;
use think\Log;
use think\Model;

class AskLiked extends Model {
    protected $table = 'ask_liked';

    /**
     * userLikeStatus
     * 查询用户问答点赞状态
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param int $uid 用户id
     * @param int $askId 问题id
     * @return int
     */
    public static function userLikeStatus($uid, $askId)
    {
        $data = self::where('ask_id', $askId)
            ->where('user_id', $uid)
            ->count();

        if ($data) {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * liked
     * 问答点赞数据处理
     *
     * @author zhengkai
     * @date 2018-03-05
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @return bool
     */
    public static function liked($uid, $askId)
    {
        $status = self::userLikeStatus($uid, $askId);
        $num = Ask::getSingleField($askId, 'like_num');

        Db::startTrans();
        try {
            if ($status) {
                // 删除已有点赞记录
                Db::query("delete from ask_liked where ask_id=:ask_id and user_id=:user_id", ['ask_id'=>$askId, 'user_id'=>$uid]);

                // 更新问答点赞统计数据
                Db::table('ask')->where('ask_id', $askId)->update(['like_num' => ($num-1)]);
            } else {
                // 新增点赞记录
                /*self::create([
                    'ask_id'  =>  $askId,
                    'user_id' =>  $uid
                ]);*/
                Db::query("insert into ask_liked (ask_id, user_id) values ({$askId}, {$uid})");

                // 更新问答点赞统计数据
                Db::table('ask')->where('ask_id', $askId)->update(['like_num' => ($num+1)]);
            }

            Db::commit();

            return true;
        } catch (\Exception $e) {
            Log::error('问答点赞错误信息：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }
}